<template>
  <div class="content">
    <div class="top">
      <van-image width="100%" height="6rem" fit="cover" :src="shopInfo.s_picture" />
    </div>
    <div class="arrow" @click="onClickLeft">
      <van-icon name="arrow-left" />
    </div>
    <div class="center">
      <div class="pic">
        <van-image width="3rem" height="3rem" fit="cover" :src="shopInfo.s_picture" />
      </div>
      <div class="first">
        <div class="name">{{ shopInfo.s_name }}</div>
        <div class="status">{{ shopInfo.s_status == 1 ? '营业中' : '休息' }}</div>
        <div class="sixcode">{{ sixcode }}</div>
      </div>
      <div class="second">
        <div class="comment">{{ shopInfo.s_comment }}分</div>
        <div class="owner">店主:{{ shopInfo.s_owner }}</div>
        <div class="time">自{{ shopInfo.s_create_time }}</div>
      </div>
      <div class="third">
        <div class="van-ellipsis introduction">{{ shopInfo.s_introduction }}</div>
      </div>
    </div>
    <div class="main">
      <div class="siderbar" ref="container">
        <van-sticky :offset-top="0" :container="container">
          <van-sidebar v-model="active" @change="onChange">
            <van-sidebar-item v-for="item in siderbarList" :title="item.title"
              :badge="item.count == 0 ? '' : item.count" />
          </van-sidebar>
        </van-sticky>
      </div>
      <div class="right_content">
        <van-index-bar :index-list="indexList" ref="siderbar">
          <div v-for="item in siderbarList">
            <van-index-anchor :index="item.title">{{ item.title }}</van-index-anchor>
            <div v-for="item1 in item.commodity">
              <lazy-component>
                <van-card :price="item1.mprice" :desc="item1.mintro" :title="item1.mname" :thumb="item1.mpic"
                  :lazy-load="true">
                  <template #tags>
                    <van-tag plain type="danger">月销{{ item1.msales }}</van-tag>
                    <van-tag plain type="warning">库存{{ item1.mstock }}</van-tag>
                  </template>
                  <template #footer>
                    <van-stepper v-model="item1.num" theme="round" button-size="18" disable-input allow-empty
                      default-value="0" :show-minus="item1.num == 0 ? false : true" min="0" @change="settlement"
                      :show-input="item1.num == 0 ? false : true" />
                  </template>
                </van-card>
              </lazy-component>
            </div>
          </div>
        </van-index-bar>
      </div>
    </div>
    <div class="bottom">
      <van-image width="100%" height="6rem" fit="cover" src="https://img.cwiyc.top/reachbottom.webp" />
      <div class="text">
        到底啦！！！
      </div>
    </div>
    <div class="bbb">
      <van-submit-bar :price="total" button-text="结算" @submit="onSubmit">
        <van-badge :content="amount" max="99">
          <van-image @click="showbox" width="3rem" height="3rem" fit="cover" src="https://img.cwiyc.top/box.jpg" />
        </van-badge>
      </van-submit-bar>
    </div>
    <div class="pop">
      <van-action-sheet v-model:show="show" title="已选商品">
        <van-cell :title="item.mname" v-for="item in choosedList">
          <template #right-icon>
            <van-stepper v-model="item.num" theme="round" button-size="18" disable-input allow-empty default-value="0"
              :show-minus="item.num == 0 ? false : true" min="0" @change="settlement"
              :show-input="item.num == 0 ? false : true" />
            <div style="position:absolute;top:2rem;left: 16rem;font-size: 13px;font-weight: 500;color: tomato;">
              ￥{{ (item.mprice * item.num).toFixed(2) }}</div>
            <van-image width="2.5rem" height="2.5rem" fit="cover" :src="item.mpic" />
          </template>
        </van-cell>
        <van-cell>
          <template #right-icon>
            <div>合计:￥{{ total / 100 }}</div>
            <van-button @click="clearBox" style="position: absolute; right:1rem;" icon="delete-o" type="plain"
              size="mini">清空</van-button>
          </template>
        </van-cell>
      </van-action-sheet>
    </div>
    <van-overlay :show="overlayshow" @click="overlayshow = false">
      <div class="wrapper" @click.stop>
        <div class="block">
          请先选择店铺
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { getCurrentInstance } from '@vue/runtime-core';
import { useRouter } from 'vue-router'
const request = require('@/network/request').default;
import { dateFormat } from '@/utils/time'
import bus from 'vue3-eventbus'
import { useStore } from 'vuex'

export default {
  name: 'Records',
  props: [],
  setup(props, context) {
    const active = ref(0);
    const onClickLeft = () => history.back();
    const shopInfo = ref([]);
    const siderbarList = ref([]);
    const indexList = ref([]);
    const indexLists = ref([])
    const index = ref(0)
    const total = ref(0)
    const amount = ref(0)
    const show = ref(false);
    const choosedList = ref([]);
    const overlayshow = ref(false)
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const container = ref(null);
    const store = useStore();
    const sixcode = ref('')
    bus.emit('routerInfo', { active: router.currentRoute._value.name })
    onMounted(function () {
      if (store.getters['cart/getshopInfo'].s_name) {
        getData()
      }
      else {
        let code = localStorage.getItem('shopcode')
        if (!router.currentRoute._value.query.code && !code) {
          overlayshow.value = true
          setTimeout(() => {
            history.back()
          }, 1000)
        }
        if (router.currentRoute._value.query.code) {
          sixcode.value = router.currentRoute._value.query.code
          findShop(router.currentRoute._value.query.code)
        }
        else {
          sixcode.value = code
          findShop(code)
        }
      }
    })
    onUnmounted(() => {
      saveData()
    })
    function saveData() {
      store.commit('cart/saveshopInfo', shopInfo.value)
      store.commit('cart/savesiderbarList', siderbarList.value)
      store.commit('cart/savetotal', total.value)
      store.commit('cart/saveamount', amount.value)
      store.commit('cart/savechoosedList', choosedList.value)
    }
    function getData() {
      shopInfo.value = store.getters['cart/getshopInfo']
      siderbarList.value = store.getters['cart/getsiderbarList']
      total.value = store.getters['cart/gettotal']
      amount.value = store.getters['cart/getamount']
      choosedList.value = store.getters['cart/getchoosedList']
    }
    function findShop(sixcode) {
      let shop = {
        ssixcode: sixcode
      }
      request.post('/getshop', shop).then(res => {
        //console.log(res)
        if (res.code == -1) {
        } else if (res.code == 0) {
          shopInfo.value = {
            s_name: res.data.sname,
            s_create_time: res.data.screatetime,
            s_picture: res.data.spicture,
            s_comment: res.data.scomment,
            s_introduction: res.data.sintroduction,
            s_status: res.data.sstatus,
            s_owner: res.data.sowner
          }
          findMeal(res.data.sid)
        }
      })
    }
    function findMeal(msid) {
      let meal = {
        msid: msid
      }
      request.post('/getmeal', meal).then(res => {
        //console.log(res)
        if (res.code == -1) {
        } else if (res.code == 0) {
          let oldVa = res.data[0].mtype
          let oldarr = []
          res.data.forEach((item, index) => {
            if (item.mtype != oldVa) {
              siderbarList.value.push({
                title: oldVa,
                count: 0,
                commodity: oldarr
              })
              oldarr = []
            }
            if (index == res.data.length - 1 && item.mtype == oldVa) {
              oldarr.push(item)
              siderbarList.value.push({
                title: oldVa,
                count: 0,
                commodity: oldarr
              })
              oldarr = []
            }
            if (index == res.data.length - 1 && item.mtype != oldVa) {
              oldarr.push(item)
              siderbarList.value.push({
                title: item.mtype,
                count: 0,
                commodity: oldarr
              })
              oldarr = []
            }
            oldarr.push(item)
            oldVa = item.mtype
          })
          siderbarList.value.forEach(item => {
            indexLists.value.push(item.title)
          })
        }
      })
    }

    const onChange = (index1) => {
      if (process.env.NODE_ENV == 'development')
        currentInstance.ctx.$refs.siderbar.scrollTo(indexLists.value[index1])
      else
        currentInstance.appContext.config.globalProperties.$refs.siderbar.scrollTo(indexLists.value[index1])
    };
    const settlement = () => {
      total.value = 0
      amount.value = 0
      let temp = 0
      siderbarList.value.forEach(item1 => {
        temp = 0
        item1.commodity.forEach(item2 => {
          if (item2.num != 0) {
            total.value += item2.num * item2.mprice * 100
            amount.value += item2.num
            temp += item2.num
          }
        })
        item1.count = temp
      });
      setTimeout(() => {
        bianli()
      }, 100);
    }
    const clearBox = () => {
      choosedList.value = []
      siderbarList.value.forEach(item1 => {
        item1.commodity.forEach(item2 => {
          item2.num = 0
        })
      });
    }
    const showbox = () => {
      show.value = !show.value
      bianli()
    }
    function bianli() {
      choosedList.value = []
      siderbarList.value.forEach(item1 => {
        item1.commodity.forEach(item2 => {
          if (item2.num != 0) {
            choosedList.value.push(item2)
          }
        })
      });
    }
    const onSubmit = () => {
      let date = new Date()
      let order = {
        orealid: (new Date()).getTime() + 7758258,
        ocreatetime: dateFormat("YYYY-mm-dd HH:MM:SS", date),
        ototalprice: total.value / 100,
        ostatus: 0,
        ouid: JSON.parse(localStorage.getItem('userInfo')).uid
      }
      // console.log(order)
      request.post('/createorder', order).then(res => {
        if (res.code == -1) {
          //console.log(res)
        } else if (res.code == 0) {
          console.log(res)
          let final = []
          choosedList.value.forEach(item => {
            final.push({
              odmid: item.mid,
              odmcount: item.num,
              odoid: res.data.oid
            })
          })
          request.post('/createod', final).then(ress => {
            if (ress.code == -1) {
              //console.log(ress)
            } else if (ress.code == 0) {
              console.log(ress)
              clearBox()
              setTimeout(() => {
                router.push("/order")
              }, 1000)
            }
          })
        }
      })
    }
    return {
      active,
      shopInfo,
      onClickLeft,
      siderbarList,
      indexList,
      onChange,
      index,
      amount,
      total,
      settlement,
      onSubmit,
      show,
      showbox,
      choosedList,
      clearBox,
      overlayshow,
      currentInstance,
      container,
      sixcode
    };
  },
}
</script>

<style scoped lang="scss">
.content {
  height: 100%;
  background-color: rgb(240, 236, 236);

  .arrow {
    position: absolute;
    color: #fff;
    top: 1rem;
    left: 0.5rem;
    font-size: larger;
  }

  .center {
    width: 20rem;
    height: 5.6rem;
    border-radius: 0.8rem;
    position: relative;
    top: -2.8rem;
    margin: 0 auto;
    background-color: #fff;

    // padding: 5px;
    .pic {
      position: absolute;
      height: 50%;
      right: 0.8rem;
      top: 0.8rem;
      border-radius: 0.3rem;
      overflow: hidden;
    }

    .first {
      display: flex;

      .name {
        font-size: 18px;
        padding: 8px 12px 0 12px;
        font-weight: bold;
      }

      .status {
        color: #fff;
        background-color: rgb(42, 176, 230);
        border-radius: 8px;
        align-self: center;
        padding: 0 2px 0 2px;
        font-size: 12px;
        margin-top: 8px;
      }

      .sixcode {
        position: absolute;
        right: 5rem;
        top: 0.8rem;
        font-weight: bold;
      }
    }

    .second {
      display: flex;

      .comment {
        color: rgb(232, 116, 23);
        font-size: 10px;
        font-weight: bold;
        padding: 5px 0 5px 12px;
      }

      .owner {
        color: rgb(167, 152, 140);
        font-size: 10px;
        font-weight: bold;
        padding: 5px 0 5px 12px;
      }

      .time {
        color: rgb(167, 152, 140);
        font-size: 10px;
        font-weight: bold;
        padding: 5px 0 5px 12px;
      }
    }

    .third {
      .introduction {
        font-size: small;
        padding: 3px 0 5px 12px;
        color: rgb(137, 135, 135);
      }
    }
  }

  .main {
    position: relative;
    display: flex;
    width: 100%;
    top: -2.7rem;

    .siderbar {
      width: 21%;
      position: sticky;
      top: 3rem;
      height: 85vh;
    }

    .right_content {
      width: 78%;
      position: relative;
      left: 1%;
      // top: -18rem;
    }
  }

  .bottom {
    position: relative;
    top: -2.7rem;

    .text {
      position: absolute;
      font-weight: bold;
      bottom: 5rem;
      left: 50%;
      transform: translate(-50%);
    }
  }

  .bbb {

    .badge {
      position: absolute;
      bottom: 2.5rem;
      right: 3rem;
    }
  }

  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;

    .block {
      // width: 120px;
      // height: 120px;
      // background-color: #fff;
      color: #fff;
    }
  }

}
</style>